package com.wechat.controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.xiezc.InitializeListerner;
import org.xiezc.annotation.Inject;
import org.xiezc.entity.WechatConfig;
import org.xiezc.entity.respMsg.BaseRespMsg;
import org.xiezc.servlet.MyHttpServlet;
import org.xiezc.util.RequestUtil;
import org.xiezc.util.SignUtil;

import com.wechat.service.HandleMsgService;

@WebServlet("/chat")
public class WechatServlet extends MyHttpServlet {
	private static Logger logger=Logger.getLogger(WechatServlet.class);
	
	private static final long serialVersionUID = 1L;
	private WechatConfig wechatConfig = InitializeListerner.wechatConfig;

	@Inject
	private HandleMsgService handleMsgService;

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		req.setCharacterEncoding("utf-8");
		resp.setCharacterEncoding("utf8");
		// 获得请求中的所有参数
		RequestUtil requestUtil = RequestUtil.getInstance(req);
		Map<String, String> reqMap = requestUtil.getReqMap();
		req.setAttribute("reqMap", reqMap);
		// 处理消息的请求
		BaseRespMsg baseRespMsg = handleMsgService.handleMsg(reqMap);
		logger.debug("baseRespMsg是否为空"+baseRespMsg+"   ToUserName:"+reqMap.get("ToUserName"));
		
		baseRespMsg.setFromUserName(reqMap.get("ToUserName"));
		baseRespMsg.setToUserName(reqMap.get("FromUserName"));
		PrintWriter pw = resp.getWriter();
		String respXml= baseRespMsg.toXml();
		/*try {
			respXml=InitializeListerner.wXBizMsgCrypt.encryptMsg(respXml, requestUtil.getTimestamp(),requestUtil.getNonce());
		} catch (AesException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}*/
		pw.print(respXml);
		pw.flush();
		pw.close();
	}

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		req.setCharacterEncoding("UTF-8");
		resp.setCharacterEncoding("UTF-8");
		String signature = req.getParameter("signature");
		String timestamp = req.getParameter("timestamp");
		String nonce = req.getParameter("nonce");
		if (SignUtil.checkSignature(wechatConfig.getToken(), signature, timestamp, nonce)) {
			PrintWriter out = resp.getWriter();
			out.print(req.getParameter("echostr"));
			out.close();
		}
	}

	public HandleMsgService getHandleMsgService() {
		return handleMsgService;
	}

	public void setHandleMsgService(HandleMsgService handleMsgService) {
		this.handleMsgService = handleMsgService;
	}
}
